<?php

namespace app\common\model;

use think\Db;
use think\Log;
use wxopen\WxComponentService;

/**
 *   数据回传
*/

class Track extends Base{
	
	/**
      * toutiao [头条橙子建站付费回传https://bytedance.feishu.cn/docs/doccnUuX9cx00CTkxSVZhAQ4LVg
		小说加粉模糊归因-字节提供归因方案（对外版3.0） -橙子]
      *
	  * @param type $type   [in_wechat_login (代表微信内注册)]
	  * @param type $type   [in_wechat_pay (代表微信内付费)]
	  * @param type $openid [openid，注册/付费时用户的open id，in_wechat_login是为必填]
	  * @param type $order  [订单数据，in_wechat_pay 是为必填]
      *
      * @return type
    **/
	public function toutiao($type="in_wechat_login",$openid='',$order=array()) {

		$header = array(
			'Content-Type: application/json',
		);
		$url = "https://analytics.oceanengine.com/api/v1/track";
		//$url = "https://analytics.oceanengine.com/api/v1/track/wechat";

		$uid = $order["agentid"];
		$wxmpid= $order["wxmpid"];
		$info = db('wxmp')->where(array('id'=>$wxmpid,'status'=>1))->find();
		$source = $info["nickname"];
		$wxaccount_id = $info["wechat"];
		$wxapp_id = $info["appid"];
		
		if($order){
			$bookid = $order['articleid'];
			$money = $order['money']*100;
			$openid = $order['openid'];
		}else{
			$money = 0;
			$bookid = 0;
		}
		
		//回传配置
		$config = db('track')->where(array('uid'=>$uid,'type'=>1,'wxmpid'=>$wxmpid,'status'=>1))->find();
		//回传充值类型
		
		if($config&&in_array(1,explode(",",$config["toutiao_type"]))){
			$track_percent = 0;
			$note = '';
			$status = 1;

			if(empty($order)){
				return false;
			}
			
			$condition = $this->condition($config,$order,'is_toutiaocz_track');
			//var_dump($condition);exit();
			if($condition){
				$track_percent = $condition['track_percent'];
				$note = $condition['note'];
				$status = $condition['status'];
				if($condition['status']==1){
					$param = array(
						"_legacy_event_type"=>$type, //事件类型，必传
						"properties"=>array(
							"we_chat_official_account_id"=>$wxaccount_id, //微信号，必传
							"we_chat_app_id"=>$wxapp_id, //微信appid，必传
							"amount"=>$money, //付费金额 单位分
							"book_id"=>$bookid, //书id，选传
							"source"=>$source,//来源，必传
						),
						"context"=>array(
							"ip"=>$order['ip'], //注册/付费时用户的ip，必传
							"userAgent"=>$order['ua'], //注册/付费时用户的ua，必传
							"ad"=>array(
								"attributed"=>"false" //直接传fasle，必传
							),
							"device"=>array(
								"open_id"=>$openid//注册/付费时用户的open id，必传
							),
						),
						"timestamp"=>time()
					);
					
					//回传
					$res = $this->curl_posts($url,json_encode($param),$header=array());

					//Log::info(date("Y-m-d H:i:s")."充值回传成功");
					//Log::info($param);
					if($res['success']){
					    
					   // if(isset($order['out_trade_no'])){
        //                 $orderval = $order['out_trade_no'];
        //             }else{
        //                 $orderval = $order['ua'];
        //             }
        //             file_put_contents(ROOT_PATH."checkquery.log",date('Y-m-d H:i:s')."$orderval".json_encode($param).PHP_EOL,FILE_APPEND);
					    
						//更新订单回传状态
						Db::name('order')->where('id='.$order['id'])->update(['is_toutiaocz_track'=>1]);
						//Log::info($res);
						file_put_contents(ROOT_PATH."track_toutiao.log",date('Y-m-d H:i:s')."抖音付费阅读回传值".json_encode($param).PHP_EOL,FILE_APPEND);
						file_put_contents(ROOT_PATH."track_toutiao.log",date('Y-m-d H:i:s')."抖音付费阅读回传返回值:".json_encode($res).PHP_EOL,FILE_APPEND);
					}else{
					    //Log::info($res);
					    file_put_contents(ROOT_PATH."track_toutiao.log",date('Y-m-d H:i:s')."抖音付费阅读回传值".json_encode($param).PHP_EOL,FILE_APPEND);
					    file_put_contents(ROOT_PATH."track_toutiao.log",date('Y-m-d H:i:s')."抖音付费阅读回传返回值:".json_encode($res).PHP_EOL,FILE_APPEND);
					}
				}
			}
			
			$this->track_log($config,$track_percent,$order,$status,$note);
		
		}
		return true;
	}

	
	/**
      * toutiao_login [头条注册回传]
      *
      * @param type $openid    [desc]
      * @param type $channelid [desc]
      * @param type $appid    [desc]
      *
      * @return type
    **/
	public function toutiao_login($openid,$appid) {
		$header = array(
			'Content-Type: application/json',
		);
		$url = "https://analytics.oceanengine.com/api/v1/track";
        $str = $openid.'-'.$appid;
        file_put_contents(ROOT_PATH."track_toutiao_third.log",date('Y-m-d H:i:s')."抖音付费阅读回传值".json_encode($str).PHP_EOL,FILE_APPEND);

		$info = db('wxmp')->where(array('appid'=>$appid,'status'=>1))->find();
		$source = $info["nickname"];
		$wxaccount_id = $info["wechat"];
		$wxapp_id = $info["appid"];
		$uid = $info['uid'];
		$wxmpid = $info['id'];

		//回传配置
		$config = db('track')->where(array('uid'=>$uid,'type'=>1,'wxmpid'=>$wxmpid,'status'=>1))->find();
		//回传充值类型
		/*
		Log::info($openid);
		Log::info($uid);
		Log::info($wxmpid);
		Log::info("开始读取回传配置");
		Log::info($config);*/
		if($config&&in_array(1,explode(",",$config["toutiao_type"]))){
			$param = array(
				"_legacy_event_type"=>"in_wechat_login", //事件类型，必传
				"properties"=>array(
					"we_chat_official_account_id"=>$wxaccount_id, //微信号，必传
					"we_chat_app_id"=>$wxapp_id, //微信appid，必传
					"source"=>$source,//来源，必传
				),
				"context"=>array(
					"ip"=>get_client_ip(0), //注册/付费时用户的ip，必传
					"userAgent"=>$_SERVER['HTTP_USER_AGENT'], //注册/付费时用户的ua，必传
					"ad"=>array(
						"attributed"=>"false" //直接传fasle，必传
					),
					"device"=>array(
						"open_id"=>$openid//注册/付费时用户的open id，必传
					),
				),
				"timestamp"=>time()
			);
			//Log::info(date("Y-m-d H:i:s")."注册回传成功");
			//Log::info($param);
			$this->curl_posts($url,json_encode($param),$header=array());
		}
	}

    /**
     * toutiao_login [头条注册回传]
     *
     * @param type $openid    [desc]
     * @param type $channelid [desc]
     * @param type $appid    [desc]
     *
     * @return type
     **/
    public function toutiao_login_third($openid,$appid,$userid) {
        $header= array(
            "content-type: application/json",
        );
        $url = "https://analytics.oceanengine.com/api/v2/conversion";
        $str = $openid.'-'.$appid.'-'.$userid;
        //file_put_contents(ROOT_PATH."track_toutiao_third1.log",date('Y-m-d H:i:s')."抖音付费阅读回传值".json_encode($str).PHP_EOL,FILE_APPEND);
        $info = db('wxmp')->where(array('appid'=>$appid,'status'=>1))->find();
        $source = $info["nickname"];
        $wxaccount_id = $info["wechat"];
        $wxapp_id = $info["appid"];
        $uid = $info['uid'];
        $wxmpid = $info['id'];

        //回传配置
        $config = db('track')->where(array('uid'=>$uid,'type'=>1,'wxmpid'=>$wxmpid,'status'=>1))->find();
        //回传充值类型

        if($config&&in_array(2,explode(",",$config["toutiao_type"]))){
            file_put_contents(ROOT_PATH."track_toutiao_third2.log",date('Y-m-d H:i:s')."抖音外链注册回传开始".json_encode($userid).PHP_EOL,FILE_APPEND);
            $userinfo = db('member')->where('uid',$userid)->find();
            $ip = '';
            if($userinfo){
                $ip = $userinfo['reg_ip'];
                //注册时间
                $reg_time = $userinfo['reg_time'];
                //注册前十分钟
                $starttime = $reg_time-600;
            }
            //存在ip地址
            if($ip){
                $referral = db('track_referral')->where(array("uid"=>$uid,"wxmpid"=>$wxmpid))->select();
                $md5 = "";
                if($referral){
                    foreach ($referral as $k=>$v){
                        if($k==0){
                            $md5 .= ' `ip` ="'.$ip.'"';
                        }else{
                            $md5 .=  ' OR `ip` ="'.$ip.'"';
                        }
                    }
                }

                //获取符合条件的用户根据IP匹配(UA暂时不考虑)
                $userua = db('track_userua')->where('wxmpid','=',$wxmpid)->where('create_time','>',$starttime)->where('create_time','<',$reg_time)->where($md5)->find();
                if(!$userua){
                    file_put_contents(ROOT_PATH."track_toutiao_third2.log",date('Y-m-d H:i:s')."抖音外链注册回传-无clickid1".json_encode($userid).PHP_EOL,FILE_APPEND);
                    return false;
                }

                if($userua['clickid']){
                    //回传配置开始
                    $clickid = $userua['clickid'];
                    $data = json_encode(array(
                        "event_type" => "active_register",
                        "context" => array(
                            "ad" => array(
                                "callback" =>$clickid,
                            )
                        ),
                        "timestamp" =>(int)(time()."000")
                    ));
                    $header= array(
                        "content-type: application/json",
                    );
                    $url = "https://analytics.oceanengine.com/api/v2/conversion";
                    //回传配置结束

                    //更新对应信息
                    $dataup['uid'] = $userid;
                    $re = db('track_userua')
                        ->where('wxmpid','=',$wxmpid)
                        ->where('create_time','>',$starttime)
                        ->where('create_time','<',$reg_time)
                        ->where($md5)
                        ->update($dataup);
                    file_put_contents(ROOT_PATH."track_toutiao_third2.log",date('Y-m-d H:i:s')."抖音外链注册更新记录表".json_decode($re)."--uid--".$userid.PHP_EOL,FILE_APPEND);
                    
                    $res = $this->curl_posts($url,$data,$header);
                    if($res['code']){
                        $this->success($res);
                        file_put_contents(ROOT_PATH."track_toutiao_third2.log",date('Y-m-d H:i:s')."抖音外链注册回传成功1".json_encode($res)."--uid--".$userid.PHP_EOL,FILE_APPEND);
                    }else{
                        file_put_contents(ROOT_PATH."track_toutiao_third2.log",date('Y-m-d H:i:s')."抖音外链注册回传成功2".json_encode($res)."--uid--".$userid.PHP_EOL,FILE_APPEND);
                    }


                }else{
                    file_put_contents(ROOT_PATH."track_toutiao_third2.log",date('Y-m-d H:i:s')."抖音外链注册回传-无clickid2".json_encode($userid).PHP_EOL,FILE_APPEND);
                }

            }

        }

    }

	/**
		字节跳动 自定义落地页数据回传

		转化回传 API 对接
		https://event-manager.oceanengine.com/docs/8650/app_api_docs/

	**/
	public function activate($order) {
		$uid = $order["agentid"];
		$wxmpid= $order["wxmpid"];
		//Log::info(date("Y-m-d H:i:s")."数据回传配置信息----uid:".$uid."----wxmpid:".$wxmpid."----UA:".$order['ua']."----IP:".$order['ip']."----订单数据:".json_encode($order));
		//回传配置
		$config = db('track')->where(array('uid'=>$uid,'type'=>1,'wxmpid'=>$wxmpid,'status'=>1))->find();
		
		if($config&&in_array(2,explode(",",$config["toutiao_type"]))){

		    //订单不存在返回false
			if(empty($order)){
				return false;
			}

			//订单查询
            $backorder= Db::name('order')->where('id='.$order['id'])->find();
			if(!$backorder){
                file_put_contents(ROOT_PATH."track_third.log",date('Y-m-d H:i:s')."订单不存在".$order['id'].PHP_EOL,FILE_APPEND);
                return false;
            }
			//已经回传的返回false，避免重复回传
			if($backorder['is_toutiao_track']==1){
                file_put_contents(ROOT_PATH."track_third.log",date('Y-m-d H:i:s')."订单已经回传".$order['id'].PHP_EOL,FILE_APPEND);
                return false;
            }

			//获取当前用户UA
			preg_match_all("@Mozilla/5.0 \((.*?)\) AppleWebKit@",$order['ua'],$ua);
			//Log::info(date("Y-m-dH:I:s")."数据回传中UA:".$ua[1][0]);
			//获取落地页信息
			$referral = db('track_referral')->where(array("uid"=>$uid,"wxmpid"=>$wxmpid))->select();

			//获取订单用户信息
            $userid = $order["uid"];
            $userinfo = db('member')->where('uid','=',$userid)->find();
            //注册ip地址
            $ip = $userinfo['reg_ip'];
            //注册时间
            $reg_time = $userinfo['reg_time'];
            $starttime = $reg_time-900;

            //IP限制条件开始
            $md5 = "";
            if($referral){
                foreach ($referral as $k=>$v){
                    if($k==0){
                        $md5 .= ' `ip` ="'.$ip.'"';
                    }else{
                        $md5 .=  ' OR `ip` ="'.$ip.'"';
                    }
                }
            }
            //IP限制条件结束
            $note = '';
            $track_percent = 0;

            file_put_contents(ROOT_PATH."track_third.log",date('Y-m-d H:i:s')."抖音付费阅读外链回传开始".json_encode($order).$md5.PHP_EOL,FILE_APPEND);
            //获取符合条件的用户UA
            $userua = db('track_userua')->where('create_time','>',$starttime)->where('create_time','<',$reg_time)->where($md5)->order('create_time desc')->find();

            if(!$userua){
                file_put_contents(ROOT_PATH."track_third.log",date('Y-m-d H:i:s')."clickid不存在1".$order['id'].$md5.PHP_EOL,FILE_APPEND);
                $status = 0;
                $note = "未接收到clickid";

            }else{
            //开始回传
                if($userua['clickid']){
                    //是否符合回传配置中的条件
                    $condition = $this->condition($config,$order,'is_toutiao_track');
                    if($condition){
                        $track_percent = $condition['track_percent'];
                        if($condition['status']==1){
                            $data = json_encode(array(
                                "event_type" => "active_pay",
                                "context" => array(
                                    "ad" => array(
                                        "callback" =>$userua['clickid'],
                                        "match_type" =>0
                                    )
                                ),
                                "properties" => array(
                                    "pay_amount" =>$order['money']
                                ),
                                "timestamp" =>(int)(time()."000")
                            ));
                            $header= array(
                                "content-type: application/json",
                            );
                            $url = "https://analytics.oceanengine.com/api/v2/conversion";
                            $res = $this->curl_posts($url,$data,$header);
                            if($res["code"]==0){
                                //Log::info(date("Y-m-dH:I:s")."数据回传成功");
                                Db::name('order')->where('id='.$order['id'])->update(['is_toutiao_track'=>1]);
                                $status = 1;
                            }else{
                                $status = 0;
                            }
                        }else{
                            $note = $condition['note'];
                            $status = 0;
                        }
                    }
                    file_put_contents(ROOT_PATH."track_third.log",date('Y-m-d H:i:s')."抖音付费阅读外链回传".$note.$order['id'].PHP_EOL,FILE_APPEND);
                }else{
                    $status = 0;
                    $note = "未接收到clickid";
                    file_put_contents(ROOT_PATH."track_third.log",date('Y-m-d H:i:s')."clickid不存在2".$order['id'].PHP_EOL,FILE_APPEND);
                }
            }
            //结束回传

            //写回传日志表
			$track_log = [
				"uid"=>$order['uid'],
				"status"=>$status,
				"update_time"=>time(),
				"create_time"=>time(),
				"out_trade_no"=>$order['out_trade_no'],
				"login_ip"=>$order['ip'],
				"pay_time"=>$order['update_time'],
				"reg_time"=>db('member')->where("uid",$order['uid'])->value('reg_time'),
				"money"=>$order['money'],
				"adid"=>$userua['adid'],
				"clickid"=>$userua['clickid'],
				"link"=>$userua['link'],
				"tid"=>$userua['tid'],
				"trackid"=>$config['id'],
				"track_percent"=>$track_percent,
				"config_percent"=>$config['scale']*10,
				"note"=>$note,
			];
			db('track_log')->insert($track_log);
		}

	}

	/**
      * weibo [微博数据回传]
      *
      * @param type $type  [激活后的数据行为 5:微信关注 6：微信付费]
      * @param type $order [订单数据,回传微信付费时使用]
	  * @param type $appid [微信appid,回传关注数据时使用]
      *
      * @return type
    **/
	public function weibo($type=5,$order=array(),$appid='') {

		if(!empty($appid)){
			$info = db('wxmp')->where(array('appid'=>$appid,'status'=>1))->find();
			$uid = $info['uid'];
			$wxmpid = $info['id'];
		}
		if(!empty($order)){
			$uid = $order["agentid"];
			$wxmpid= $order["wxmpid"];
		}
		
		//回传配置
		$config = db('track')->where(array('uid'=>$uid,'type'=>2,'wxmpid'=>$wxmpid,'status'=>1))->find();
		if($config){
			if($type==5){
				//Log::info("微博关注数据回传配置");
				preg_match_all("@Mozilla/5.0 \((.*?)\) AppleWebKit@",$_SERVER['HTTP_USER_AGENT'],$uaparam);
				$ua = $uaparam[1][0];
				$ip=request()->ip();
				$md5 = md5($ip.$ua);
				//匹配一个小时之内点击微博广告进入的用户
				//$userua_wb = db('track_userua_wb')->where("md5",$md5)->whereTime('create_time','-1 hours')->find();
				//匹配一天之内点击微博广告进入的用户
				$userua_wb = db('track_userua_wb')->where("md5",$md5)->whereTime('create_time','-1 days')->find();
				if(!empty($userua_wb["IMP"])){
					$url="http://appmonitor.biz.weibo.com/sdkserver/active?IMP=".$userua_wb["IMP"]."&action_type=".$type."&active_time=".time();
					$this->curl_get($url);
                    file_put_contents(ROOT_PATH."track_weibo.log",date('Y-m-d H:i:s')."微博加粉回传".$userua_wb["IMP"].PHP_EOL,FILE_APPEND);
				}
			}else{
				
				if(empty($order)){
					return false;
				}
				//获取当前用户UA
				preg_match_all("@Mozilla/5.0 \((.*?)\) AppleWebKit@",$order['ua'],$ua);
				$md5 = md5($order['ip'].$ua[1][0]);

				//匹配一个小时之内点击微博广告进入的用户
				//$userua_wb = db('track_userua_wb')->where("md5",$md5)->whereTime('create_time','-1 hours')->find();
				//匹配一天之内点击微博广告进入的用户
				$userua_wb = db('track_userua_wb')->where("md5",$md5)->whereTime('create_time','-1 days')->find();
				if(!empty($userua_wb["IMP"])){
					$track_percent = 0;
					$note = '';
					$status = 0;
					$condition = $this->condition($config,$order,'is_weibo_track');
					
					$track_percent = $condition['track_percent'];
					$note = $condition['note'];
					$status = $condition['status'];
					if($condition['status']==1){
						$url="http://appmonitor.biz.weibo.com/sdkserver/active?IMP=".$userua_wb["IMP"]."&action_type=".$type."&active_time=".time()."&price=".$order['money'];
						$this->curl_get($url);
						Db::name('order')->where('id='.$order['id'])->update(['is_weibo_track'=>1]);
						$status = 1;
					}else{
						$note = $condition['note'];
						$status = 0;
					}
					$this->track_log($config,$track_percent,$order,$status,$note);
                    file_put_contents(ROOT_PATH."track_weibo.log",date('Y-m-d H:i:s')."微博付费回传".$userua_wb["IMP"].PHP_EOL,FILE_APPEND);
				}
			}
		}
	}
	
	/**
      * tengxun [腾讯数据回传]
      *
      * @param type $order [订单信息]
      * @param type $type  [回传平台 1:MP 2:GDT]
      *
      * @return type
    **/

	public function tengxun($order,$type) {
		$uid = $order["agentid"];
		$wxmpid= $order["wxmpid"];
		//Log::info(date("Y-m-d H:i:s")."数据回传配置信息----uid:".$uid."----wxmpid:".$wxmpid."----UA:".$order['ua']."----IP:".$order['ip']."----订单数据:".json_encode($order));
		//回传配置
		
		$config = db('track_tengxun')->where(array('uid'=>$uid,'platform'=>$type,'wxmpid'=>$wxmpid,'status'=>1))->find();
		
		if(!empty($config) && $config['status']==1){
			if($config['mode']==2){//全量回传
				if($config['paytype']==1){
					$order_object ="read_4";
				}elseif($config['paytype']==2){
					$order_object ="read_2";
				}elseif($config['paytype']==3){
					$order_object ="read_3";
				}elseif($config['paytype']==4){
					$order_object ="read_1";
				}else{
					$order_object ="read_0";
				}
				$purchase_object =1;
			}elseif($config['mode']==1){//非全量回传
				if($config['paytype']==1){
					$order_object ="read_4";
					$purchase_object ="read_4";
				}elseif($config['paytype']==2){
					$order_object ="read_2";
					$purchase_object ="read_2";
				}elseif($config['paytype']==3){
					$order_object ="read_3";
					$purchase_object ="read_3";
				}elseif($config['paytype']==4){
					$order_object ="read_1";
					$purchase_object ="read_1";
				}else{
					$order_object ="read_0";
					$purchase_object ="read_0";
				}
			}
			
			
			if(!empty($wxmpid)&&!empty($order['openid'])){
				$auto = db('wxmp')->where(['uid'=>$uid,'id'=>$wxmpid,'status'=>1])->field('appid,autoconfig,open_appid')->find();

				
				//公众号自动配置
				if(array_key_exists("autoconfig",$auto)){
					$account = db('wxopen_account')->where('appid',$auto['open_appid'])->find();
					$wxComponentConfig = array(
						'component_appid'=>$account["appid"],
						'component_appsecret'=>$account["appsecret"],
						'encodingAesKey'=>$account["encodingKey"],
						'token'=>$account["token"]
					);
					
					$wxAuth = new WxComponentService($wxComponentConfig);
					$wechat = $wxAuth->getWechat($auto["appid"]);
					
					if($order['articleid']){
						$product_name =get_novel($order['articleid'],'title')."-爽读云";
						$product_id = $order['articleid'];
						$url = get_agent_domain($uid,0,$wxmpid)."/book/info/id/".$order['articleid'];
					}else{
						$product_name ="充值活动-书城";
						$product_id = "";
						$url = get_agent_domain($uid,0,$wxmpid)."/pay/index";
					}
					
					
					
					//将用户的首次充值分别回传到「下单」和「付费」字段
					$condition = $this->condition_tx($config,$order);
					if($condition){
						$res = $wechat->addUserAction($type,$url,$config['user_action_set_id'],"COMPLETE_ORDER",$auto["appid"],$order['openid'],$order_object,$product_name,$product_id,$order['money']*100);
						if($res){
							$is_complete_order = 1;
						}else{
							$is_complete_order = 0;
						}
					}else{
						$is_complete_order = 2;
					}
					
					
					//将用户的第二次或以上充值行为回传到「付费」。
					//Log::info("将用户的第二次或以上充值行为回传到「付费」");
					$res = $wechat->addUserAction($type,$url,$config['user_action_set_id'],"PURCHASE",$auto["appid"],$order['openid'],$purchase_object,$product_name,$product_id,$order['money']*100);//付费
					
					if($res["errcode"]==0){
						//Log::info("将用户的第二次或以上充值行为回传到「付费」回传成功");
						$track_log = [
							"uid"=>$order['uid'],
							"appid"=>$auto["appid"],
							"openid"=>$order['openid'],
							"useractionid"=>$config['user_action_set_id'],
							"url"=>$url,
							"status"=>1,
							"update_time"=>time(),
							"create_time"=>time(),
							"out_trade_no"=>$order['out_trade_no'],
							"pay_time"=>$order['update_time'],
							"money"=>$order['money'],
							"tid"=>$config['id'],
							"is_complete_order"=>$is_complete_order,
							"product_name"=>$product_name,
							"product_id"=>$product_id,
							"order_object"=>$order_object
						];
						db('track_tengxun_log')->insert($track_log);
					}
				}
			}

			
		}
	}

	/**
      * baidu [百度数据回传--书城回传加粉付费]
      *
      * @param type $oweType [0粉丝关注,1付费阅读,2进入书城并阅读]
      * @param type $openid  [粉丝关注时用户的openID]
      * @param type $appid   [粉丝关注时对应的公众号appid]
      * @param type $order   [付费阅读时订单数据]
      *
      * @return type
    **/
	public function baidu($oweType=0,$openid='',$appid='',$order=array()) {
		$header = array(
			'Content-Type: application/json',
		);
		if(!empty($appid)){
            $info = db('wxmp')->where(array('appid'=>$appid,'status'=>1))->find();
            $uid = $info['uid'];
            $wxmpid = $info['id'];
        }

		if(!empty($order)){
			$uid = $order["agentid"];
			$wxmpid= $order["wxmpid"];
			$openid = $order["openid"];
		}
		

		$info = db('wxmp')->where(array('id'=>$wxmpid,'status'=>1))->find();
		$source = $info["nickname"];
		$wxapp_id = $info["appid"];
		
		//开发、测试、联调回传URL
		//$url = "yingxiaotong-offline.baidu.com/fmb-weixin/wechat/pushFanRecords";
		//线上回传URL
		$url = "yingxiaotong.baidu.com/fmb-weixin/wechat/pushFanRecords";

		//回传配置
		$config = db('track')->where(array('uid'=>$uid,'type'=>3,'wxmpid'=>$wxmpid,'status'=>1))->find();

		if(!empty($config)){
			
			//$originId = $config['originId']?$config['originId']:"青果书城";
			//$secure = $config['secure']?$config['secure']:"2xQYRRe3DIblpq3e";
			$originId = config('baidu_originid');
			$secure  = config('baidu_secure');
			$currentTime = (int)(time()."000");
			$sign = "currentTime={$currentTime}&originId={$originId}{$secure}";
			
			$post_data = [];
			$post_data['originId'] = $originId;
			$post_data['currentTime'] = $currentTime;
			$post_data['sign'] = md5($sign);
			
			//付费阅读
			if($oweType==1){
				$track_percent = 0;
				$note = '';
				$status = 0;
				$condition = $this->condition($config,$order,'is_baidu_track');
				
				$track_percent = $condition['track_percent'];
				$note = $condition['note'];
				$status = $condition['status'];
				//符合回传条件的开始回传
				if($condition['status']==1){
					$bookname="书城首页";
					$channel = "";
					$category = "未知";
					$ip = $order["ip"];
					$ua = $order["ua"];
					if(!empty($order["articleid"])){
						$book=db('novel')->where('id',$order["articleid"])->find();
						$bookname=$book['title'];
						$channel =$book['channel']==1?0:1;
						if(!empty($book["category_id"])){
							$category = db('category')->where('id',$book["category_id"])->value('title');
						}
					}
					$extra = [
						'bookName' =>$bookname,
						'payCatalogGender' =>$channel, // 书籍频道
						'payCatalog' =>$category, // 书籍题材类型
						'orderType' =>'4', // 订单类型
						'payAmount' =>$order["money"]*100,// 付费金额
					];
					$post_data['data'][] = [
						'oweType' =>$oweType,
						'applyTime' => date('Y-m-d H:i:s'),
						'accountName' =>$source,
						'openId' =>$openid,
						'ip' =>$ip,
						'userAgent' =>$ua,
						'extra' =>$extra,
						'publicId' =>$wxapp_id
					];
					//file_put_contents(ROOT_PATH."track_baidu.log",date('Y-m-d H:i:s')."付费阅读回传值".json_encode($post_data).PHP_EOL,FILE_APPEND);
					$res = $this->curl_posts($url,json_encode($post_data),$header);
					//file_put_contents(ROOT_PATH."track_baidu.log",date('Y-m-d H:i:s')."付费阅读回传返回值:".json_encode($res).PHP_EOL,FILE_APPEND);
                    file_put_contents(ROOT_PATH."track_baidu.log",date('Y-m-d H:i:s')."付费阅读回传测试".json_encode($order).PHP_EOL,FILE_APPEND);
					$status = 1;
				}else{
					$note = $condition['note'];
					$status = 0;
				}

                //匹配百度计划id
                $adid = '';
                $userinfo = db('member')->where("uid",$order['uid'])->field('reg_ip,reg_time')->find();
                if($userinfo){
                    $reg_ip = $userinfo['reg_ip'];
                    $reg_time =   $userinfo['reg_time'];
                    $starttime = $reg_time-60*15;
                    $endtime   = $reg_time;
                    //匹配用户注册前15分钟之内的记录IP
                    $result = db('track_userua_baidu')->where('ip','=',$reg_ip)->where('create_time','>=',$starttime)->where('create_time','<=',$endtime)->field('id,pid,create_time')->order('id','desc')->find();
                    if($result){
                        $adid = $result['pid'];
                    }
                }
                //匹配百度计划id

				$this->track_log($config,$track_percent,$order,$status,$note,$adid);

			}elseif($oweType==0){//粉丝关注
				$extra = [
					'bookName' =>"",
					'payCatalogGender' =>"", // 书籍频道
					'payCatalog' =>"", // 书籍题材类型
					'orderType' =>'0', // 订单类型
					'payAmount' =>0,// 付费金额
				];
				$post_data['data'][] = [
					'oweType' =>$oweType,
					'applyTime' => date('Y-m-d H:i:s'),
					'accountName' =>$source,
					'openId' =>$openid,
					'ip' =>request()->ip(),
					'userAgent' =>$_SERVER['HTTP_USER_AGENT'],
					'extra' =>$extra,
					'publicId' =>$wxapp_id
				];
				
				file_put_contents(ROOT_PATH."track_baidu.log",date('Y-m-d H:i:s')."粉丝关注回传值".json_encode($post_data).PHP_EOL,FILE_APPEND);
				$res = $this->curl_posts($url,json_encode($post_data),$header);
				file_put_contents(ROOT_PATH."track_baidu.log",date('Y-m-d H:i:s')."粉丝关注回传返回值:".json_encode($res).PHP_EOL,FILE_APPEND);
			}
		}
	}

    /**
     * oppo回传
     *
     * @param type $oweType [0粉丝关注,1付费阅读,2进入书城并阅读]
     * @param type $openid  [粉丝关注时用户的openID]
     * @param type $appid   [粉丝关注时对应的公众号appid]
     * @param type $order   [付费阅读时订单数据]
     * @return
     */
    public function oppo($type, $openid = '', $appid = '', $order=[])
    {
        if (!empty($appid)) {
            $info = db('wxmp')->where(['appid' => $appid, 'status' => 1])->find();
            $uid = $info['uid'];
            $wxmpid = $info['id'];
        }

        if (!empty($order)) {
            $uid = $order['agentid'];
            $wxmpid= $order['wxmpid'];
            $openid = $order['openid'];
            $info = db('wxmp')->where(['id' => $wxmpid, 'status' => 1])->find();
        }

        if (empty($info)) return;
        $source = $info['nickname'];
        $wxappId = $info['appid'];

        $config = db('track')->where(['uid' => $uid, 'type' => 5, 'wxmpid' => $wxmpid, 'status' => 1])->find();

        if (empty($config)) return;

        //$transformType = $type == 0 ? '104' : '105';
        $transformType = '101';

        if ($type == 0) {
            // 用户关注
            $ip = request()->ip();
            $result = self::oppoCallback($transformType, $ip);
        } else {
            // 用户付费
            $condition = $this->condition($config, $order, 'is_oppo_track');
            $trackPercent = $condition['track_percent'] ?? 0;
            $note = $condition['note'];
            $status = $condition['status'] ?? 0;
            // $condition['status'] = 1;
            if ($condition['status'] == 1) {
                $ip = $order['ip'];
                $result = self::oppoCallback($transformType, $ip);
                $result = json_decode($result, true);

                if ($result['code'] == 0) {
                    db('order')->where(['id' => $order['id']])->update(['is_oppo_track' => 1]);
                }
                dump($result);die;
            }
            $this->track_log($config, $trackPercent, $order, $status, $note);
        }
    }

    // oppo 回传
    private function oppoCallback($transformType, $ip)
    {
        //OPPO账号信息:奇虎遂心(1000176887),奇虎含韵(1000176886),奇虎兴旺(1000176885),奇虎秋月(1000176884),奇虎致富(1000176883),奇虎和畅(1000176878),湖南奇虎文化(1000153991)
        $useropp = [
            1000176887 => ['id'=>'1000176887','apiid'=>'2d434b47b7eb44ff8266c6ead7e3e658','apikey'=>'446f161c7ddb470bbcb1ede42f76a028'],
            1000176886 => ['id'=>'1000176886','apiid'=>'dfcf4aadf52b4feab4cabbd96f70f8a2','apikey'=>'292f42f9939b4eb784ec16cf34f0be57'],
            1000176885 => ['id'=>'1000176885','apiid'=>'39c0d08ba2bd4e7a98a5bf2b0e1c01fe','apikey'=>'e90b2b13afad4cdbaaceeefb295e1a3c'],
            1000176884 => ['id'=>'1000176884','apiid'=>'d0cdac0d8d734e45a157dc246b807b70','apikey'=>'63bac6337c2f46fcb05a3094df4b5411'],
            1000176883 => ['id'=>'1000176883','apiid'=>'5e2ab9822a9e428698ef5b4db08baa75','apikey'=>'588b3677c6524ad4b12cf09b3643cbc4'],
            1000176878 => ['id'=>'1000176878','apiid'=>'6c9ebfba248448c68cb3249fa74acdca','apikey'=>'9219250c78db431185385e4e279a33da'],
            1000153991 => ['id'=>'1000153991','apiid'=>'b333d328b7f84ea99e098ce7d47b0a18','apikey'=>'ea15413fff7f44f68902041787e228a3']
        ];

        //根据注册ip粗略匹配用户
        $data = db('track_userua_oppo')->where(['ip' => $ip])->find();

        if ($data) {
            //获取传传值的oppoid
            $oppid = $data['oppoid'];
            if(!$oppid){
                file_put_contents(ROOT_PATH."track_oppo_oss.log",date('Y-m-d H:i:s')."注册和付费回传-oppoid不存在".PHP_EOL,FILE_APPEND);
                return '';
            }
            //获取具体账号信息
            $user = $useropp[$oppid];
            $ownerId = $user['id'];
            $apiId = $user['apiid'];
            $apiKey = $user['apikey'];

            $url = 'https://sapi.ads.oppomobile.com/v1/clue/sendData';
            $timestamp = time();
            $sign = sha1($apiId.$apiKey.$timestamp);
            $token = base64_encode($ownerId.','.$apiId.','.$timestamp.','.$sign);

            $requestData = [
                'pageId'        => (int)$data['page_id'],
                'ownerId'       => $ownerId,
                'ip'            => $ip,
                'tid'           => $data['tid'],
                'lbid'          => $data['lbid'],
                'transformType' => $transformType
            ];

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            if (is_array($requestData)) {
                $requestData = json_encode($requestData);
            }

            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $requestData);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_HTTPHEADER, [
                'Content-Type:application/json',
                'Authorization:Bearer ' . $token
            ]);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);

            $errorNo = curl_errno($curl);

            if ($errorNo) {
                return $errorNo;
            }
            curl_close($curl);
            return $result;
        }
    }


	/**
      * track_log [回传日志]
      *
      * @param type $config        [回传配置]
      * @param type $track_percent [回传百分比]
      * @param type $order         [订单数据]
	  * @param type $status         [回传状态 1：成功 0：失败]
      *
      * @return type
    **/

	public function track_log($config,$track_percent,$order,$status=1,$note='',$adid='') {
	
		$track_log = [
			"uid"=>$order['uid'],
			"status"=>$status,
			"update_time"=>time(),
			"create_time"=>time(),
			"out_trade_no"=>$order['out_trade_no'],
			"login_ip"=>$order['ip'],
			"pay_time"=>$order['update_time'],
			"reg_time"=>db('member')->where("uid",$order['uid'])->value('reg_time'),
			"money"=>$order['money'],
			"adid"=>$adid,
			"clickid"=>'',
			"link"=>'',
			"tid"=>'',
			"trackid"=>$config['id'],
			"track_percent"=>$track_percent,
			"config_percent"=>$config['scale']*10,
			"note"=>$note,
		];
		db('track_log')->insert($track_log);
	}


	public function condition($config,$order,$field) {

		$total = 0;
		
		//按照回传比例		
		$date1 = mktime(0, 0, 0, date("m"), 1, date("Y"));
		$date2 =mktime(23, 59, 59, date("m"), date("t"), date("Y"));
		$map['status'] =1;			
		$map['agentid'] =$order['agentid'];
		$map['create_time'] =array(array('gt',$date1),array('lt',$date2));
		//查询本月充值订单数
		$totalorder = Db::name('order')->where($map)->count();
		//Log::info("查询本月充值订单数".$totalorder);
		$map[$field] =1;
		//查询本月已经回传订单数
		$totaltrack = Db::name('order')->where($map)->count();
		$totaltrack = $totaltrack>0?$totaltrack:1;
		//Log::info("查询本月已经回传订单数".$totaltrack);
		//回传订单/充值订单数
		$total = round($totaltrack/$totalorder*100,0);
		

		//回传充值类型
		
		if(!empty($config["paytype"])&&$config["paytype"]!=1){
			if($config["paytype"]==2){
				$starttime = strtotime(date('Y-m-d'));
				$endtime = strtotime(date('Y-m-d 23:59:59'));
			}elseif($config["paytype"]==3){
				$starttime = time()-24*3600;
				$endtime = time();
			}elseif($config["paytype"]==4){
				$starttime = time()-72*3600;
				$endtime = time();
			}				
			$appid= db('wxmp')->where(['id'=>$config["wxmpid"],'status'=>1])->cache(true)->value('appid');
			//按条件获取关注的用户
			$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.subscribe_time','between time',[$starttime,$endtime])->column('u.uid');
			//不在条件则不关注
			if(!in_array($order['uid'],$fans)){
				return ['status'=>0,'track_percent'=>0,'note'=>'不符合回传充值条件'];
			}
		}
		
		//回传首充
		if(!empty($config["transfer_mode"])){
			//回传所有首充
			if($config["transfer_mode"]==1){
				$paynum = db('member')->where('uid',$order['uid'])->value('pay');
				if($paynum>=1){
					return false;
				}
			}else{
				//回传用户在关注当天自然日的首充
				if($config["transfer_mode"]==2){
					$starttime = strtotime(date('Y-m-d'));
					$endtime = strtotime(date('Y-m-d 23:59:59'));
				}elseif($config["transfer_mode"]==3){
					//回传用户在关注后24小时内的所有首充
					$starttime = time()-24*3600;
					$endtime = time();
					
				}elseif($config["transfer_mode"]==4){
					//回传用户在关注后72小时内的所有首充
					$starttime = time()-72*3600;
					$endtime = time();
				}
				$appid= db('wxmp')->where(['id'=>$config["wxmpid"],'status'=>1])->cache(true)->value('appid');
				//按条件获取关注的用户
				$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.subscribe_time','between time',[$starttime,$endtime])->column('u.uid');
				
				//排除不符合条件的关注
				if(!in_array($order['uid'],$fans)){
					return ['status'=>0,'track_percent'=>0,'note'=>'不符合回传首充条件'];
				}
				/*
				$paynum = db('member')->where('uid',$order['uid'])->value('pay');
				if($paynum>=1){
					return ['status'=>0,'track_percent'=>0];
				}*/
			}
		}
		//回传比例 为空则不回传
		if(empty($config["scale"])){
			return ['status'=>0,'track_percent'=>0,'note'=>'回传比例为空'];
		}
		
		if($config["scale"]<=10 && $config["scale"]>0){
			
			
			if($totalorder>0){
				
				//Log::info("回传订单/充值订单数".$total);
				//已回传的数据大于等于回传比例则不回传
				/**
				if($total>($config["scale"]*10)){
					return ['status'=>0,'track_percent'=>$total];
				}
				**/
				if($config["scale"]==1&&in_array($totalorder%10,[1]) || 
				   $config["scale"]==2&&in_array($totalorder%10,[1,6]) || $config["scale"]==3&&in_array($totalorder%10,[1,4,7]) || $config["scale"]==4&&in_array($totalorder%10,[1,2,6,7]) || $config["scale"]==5&&in_array($totalorder%10,[1,3,5,7,9]) || $config["scale"]==6&&in_array($totalorder%10,[1,2,3,6,7,8]) || $config["scale"]==7&&in_array($totalorder%10,[1,2,3,4,5,6,7]) ||
				   $config["scale"]==8&&in_array($totalorder%10,[1,2,3,4,6,7,8,9]) ||
				   $config["scale"]==9&&in_array($totalorder%10,[1,2,3,4,5,6,7,8,9]) ){
					return ['status'=>1,'track_percent'=>$total,'note'=>''];
				}elseif($config["scale"]==10){
					return ['status'=>1,'track_percent'=>$total,'note'=>''];
				}else{
					return ['status'=>0,'track_percent'=>$total,'note'=>'百分比过滤'];
				}
			}else{
				return ['status'=>1,'track_percent'=>100,'note'=>''];
			}
		}
		
		if(!empty($config["money"])){
			//订单金额小于回传金额范围则不回传
			if($order['money']<$config["money"]){
				return ['status'=>0,'track_percent'=>0,'note'=>'订单金额小于回传金额范围'];
			}
		}
		
		return ['status'=>1,'track_percent'=>$total,'note'=>''];
	}

	public function condition_tx($config,$order) {
		
		//回传充值类型
		if(!empty($config["paytype"])&&in_array($config["paytype"],[1,2])){
			if($config["paytype"]==1){
				$starttime = strtotime(date('Y-m-d'));
				$endtime = strtotime(date('Y-m-d 23:59:59'));
			}elseif($config["paytype"]==2){
				$starttime = time()-24*3600;
				$endtime = time();
			}			
			$appid= db('wxmp')->where(['id'=>$config["wxmpid"],'status'=>1])->cache(true)->value('appid');
			//按条件获取关注的用户
			$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.subscribe_time','between time',[$starttime,$endtime])->column('u.uid');
			//不在条件则不关注
			if(!in_array($order['uid'],$fans)){
				return false;
			}
		}

		//回传首充
		if(!empty($config["paytype"])&&in_array($config["paytype"],[3,4])){
			
			//回传用户在关注当天自然日的首充
			if($config["paytype"]==3){
				$starttime = strtotime(date('Y-m-d'));
				$endtime = strtotime(date('Y-m-d 23:59:59'));
			}elseif($config["paytype"]==4){
				//回传用户在关注后24小时内的所有首充
				$starttime = time()-24*3600;
				$endtime = time();
				
			}elseif($config["paytype"]==5){
				//回传用户在关注后72小时内的所有首充
				$starttime = time()-72*3600;
				$endtime = time();
			}
			$appid= db('wxmp')->where(['id'=>$config["wxmpid"],'status'=>1])->cache(true)->value('appid');
			//按条件获取关注的用户
			$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.subscribe_time','between time',[$starttime,$endtime])->column('u.uid');
			
			//排除不符合条件的关注
			if(!in_array($order['uid'],$fans)){
				return false;
			}
			
			$paynum = db('member')->where('uid',$order['uid'])->value('pay');
			if($paynum>1){
				return false;
			}
			
		}
		return true;
	}


    /**
     * novelpay [小说充值]
     *
     * @return type
     **/
    public function  novelpay($order){
        //判断订单返回
        if(!array_key_exists('articleid',$order)){return '';}
        if(!array_key_exists('money',$order)){return '';}
        $articleid = $order['articleid'];
        if(!$articleid){return '';}  //为0时不记录充值情况
        $money = $order['money'];

        //时间换算，今天0点0分0秒
        $today = date('Y-m-d');
        $date_time = strtotime($today);

        file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."支付排行榜回传值开始".json_encode($order).PHP_EOL,FILE_APPEND);

        //查询数据库是否存在记录
        $result = db('statistics_novel')->where('articleid','=',$articleid)->where('date_time','=',$date_time)->find();
        //更新
        if($result){
            $dataUp['money'] = $result['money'] + $money;
            $dataUp['update_time'] = time();
            $res = db('statistics_novel')->where('articleid','=',$articleid)->where('date_time','=',$date_time)->update($dataUp);
            //return $res;
            //添加
        }else{
            $dataIn['date_time'] = $date_time;
            $dataIn['articleid'] = $articleid;
            $dataIn['money'] = $money;
            $dataIn['create_time'] = time();
            $res = db('statistics_novel')->insertGetId($dataIn);
            //return $res;
        }

        //处理统计开始//
        file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."===============开始统计================".PHP_EOL,FILE_APPEND);
        if(!$order['id']){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."缺少订单ID".json_encode($order).PHP_EOL,FILE_APPEND);
            return '';
        }
        $orderinfo = db('order')->where(['id' => $order['id']])->find();
        if(!$orderinfo){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."缺少信息".json_encode($order).PHP_EOL,FILE_APPEND);
        }
        $is_income_track = $orderinfo['is_income_track'];
        if($is_income_track){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."订单已经统计，请勿重复统计：".$order['id'].PHP_EOL,FILE_APPEND);
            return '';
        }
        if((!$order['uid'])||(!$order['spreadid'])||(!$order['money'])){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."缺少uid或者spreadid".json_encode($order).PHP_EOL,FILE_APPEND);
            return '';
        }
        $money = (int)$order['money'];
        //注册时间
        $reg_time = '';
        //用户信息
        $resm = db('member')->where('uid','=',$order['uid'])->find();
        if(!$resm){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."缺少用户信息".json_encode($order).PHP_EOL,FILE_APPEND);
            return '';
        }
        if($resm){
            $reg_time = $resm['reg_time'];  //注册时间戳
            $paytime  = $resm['paytime']; //染色时间
        }
        if(!$reg_time){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."缺少用户注册时间".json_encode($order).PHP_EOL,FILE_APPEND);
            return '';
        }

        //推广链接信息
        $ress = db('tuiguang')->where('id','=',$order['spreadid'])->find();
        if(!$ress){
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."缺少推广链接信息".json_encode($order).PHP_EOL,FILE_APPEND);
            return '';
        }
        //推广链接用户id
        $tuid = $ress['uid'];
        //推广链接创建时间
        $tui_create_time = $ress['create_time'];
        //转化成推广链接当天凌晨时间
        $tui_create_day = date('Y-m-d',$tui_create_time);
        //推广链接生成凌晨linux时间戳
        $tui_create_time_zero = strtotime($tui_create_day);

        //今天凌晨时间
        $datetody_zero = date('Y-m-d');
        //今天凌晨的时间戳
        $timetody_zero = strtotime($datetody_zero)+1;

        //今天时间减去推广链接创建凌晨时间，算天数
        $times = $timetody_zero - $tui_create_time_zero;
        //判断相差的天数
        $days  =  $times/86400;
        $realdays  = ceil($days);

        //第几天的充值(incomeday)
        $incomeday = $realdays;
        //第几天的时间戳，或对应正式推广时间
        $showstarttime = $tui_create_time_zero + ($realdays-1)*86400;

        //perday处理开始,用户注册的凌晨时间
        $reg_date = date('Y-m-d',$reg_time);
        //用户注册的凌晨时间戳
        $reg_start_time = strtotime($reg_date);
        //今天时间时间戳
        $now_time = time();

        //now_reg_times判断相差的天数时间戳，今天时间减去用户注册注册时间
        $now_reg_times = $now_time - $reg_start_time;
        $income_old = 0;
        $income_new = 0;
        //var_dump($now_reg_times);
        if($now_reg_times<86400){
            $income_new = $money;
        }else{
            $income_old = $money;
        }

        //推广链接第一天记录是否存在
        $res = db('tuiguang_count')->where('tid','=',$order['spreadid'])->where('incomeday','=',$incomeday)->find();
        if(!$res){
            $tdata['tid'] = $order['spreadid'];
            $tdata['incomeday'] = $incomeday;
            $tdata['showstarttime'] = $showstarttime;
            $tdata['create_time'] = date('Y-m-d H:i:s',time());
            $tdata['update_time'] = date('Y-m-d H:i:s',time());
            $tdata['tuiguang_create_time'] = $tui_create_time;
            $tdata['income'] = $money;
            $tdata['income_old'] = $income_old;
            $tdata['income_new'] = $income_new;
            $tdata['uid'] = $tuid;
            $re = db('tuiguang_count')->insertGetId($tdata);
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."统计完毕-新增：".$re.PHP_EOL,FILE_APPEND);

        }else{
            if($order['is_income_track']!=1){
                //修改记录
                $tdata['income'] = $res['income'] + $money;
                $tdata['income_old'] = $res['income_old'] + $income_old;
                $tdata['income_new'] = $res['income_new'] + $income_new;
                $tdata['update_time'] = date('Y-m-d H:i:s',time());
                if(!$res['uid']){$tdata['uid'] = $tuid;}
                $re = db('tuiguang_count')->where('tid','=',$order['spreadid'])->where('incomeday','=',$incomeday)->update($tdata);
                file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."统计完毕-修改：".$re.PHP_EOL,FILE_APPEND);
            }
            //return $re;
        }
        //var_dump($re);
        if($re){
            $r = db('order')->where(['id' => $order['id']])->update(['is_income_track' => 1,'user_reg_time'=>$reg_time]);
            file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."修改订单：".$r.PHP_EOL,FILE_APPEND);
        }
        file_put_contents(ROOT_PATH."track_novelpay.log",date('Y-m-d H:i:s')."===============结束统计================统计回传值结果：".$re.PHP_EOL,FILE_APPEND);
        //处理统计结束//

    }


    public function curl_posts($url,$data,$header=array()){
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url);
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		if($header){
			curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
		}
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS,$data);
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false);
		$returns = curl_exec ( $ch );
		curl_close ( $ch );
		$result = json_decode($returns,true);
		return $result;
	}

	public function curl_get($url,$header=false){
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url);
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		if($header){
			curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
		}
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false);
		$returns = curl_exec ( $ch );
		curl_close ( $ch );
		$result = json_decode($returns,true);
		return $result;
	}
}